package com.xin.di.uav.common.utils;

import com.xin.di.uav.common.enums.ErrorEnum;
import com.xin.di.uav.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.core.convert.converter.Converter;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author LTQ
 * @version 1.0
 * @description TODO
 * @date 2020-07-21 15:35
 * @since 1.8
 */
public class BeanUtil implements Converter {

    final static Logger logger = LoggerFactory.getLogger(BeanUtil.class);

    /**
     * @param source
     * @param clazz
     * @return
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws InstantiationException
     */
    public static <T> T copyProperties(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T t = null;
        try {
            t = clazz.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, t);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return t;
    }

    /**
     * @param source
     * @param clazz
     * @return
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws InstantiationException
     */
    public static <T> List<T> copyProperties(List<?> source, Class<T> clazz) {
        if (source == null || source.size() == 0) {
            return Collections.emptyList();
        }
        List<T> res = new ArrayList<>(source.size());
        for (Object o : source) {
            T t = null;
            try {
                t = clazz.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(o, t);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            res.add(t);
        }
        return res;
    }

    @Override
    public Object convert(Object o) {
        return null;
    }

    /**
     * @param sourceList
     * @param requiredType
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T, E> List<T> convertFrom(List<E> sourceList, Class<T> requiredType) {
        return convertFrom(sourceList, requiredType, t -> {
        });
    }

    /**
     * 通过对象属性复制将源对象List转为目标对象List 并可写一段lambda表达式对目标对象进行额外处理
     *
     * @param sourceList   源对象List
     * @param requiredType 目标对象的类型
     * @param consumer     lambda函数，可对目标对象进行额外处理
     * @param <T>          目标对象泛型
     * @param <E>          源对象泛型
     * @return 目标对象
     */
    public static <T, E> List<T> convertFrom(List<E> sourceList, Class<T> requiredType, Consumer<T> consumer) {
        if (sourceList == null) {
            return null;
        }
        List<T> targetList = new ArrayList<>();
        if (!sourceList.isEmpty()) {
            sourceList.forEach(source -> targetList.add(convertFrom(source, requiredType, consumer)));
        }
        return targetList;
    }

    /**
     * 通过对象属性复制进行对象的转换,并可写一段lambda表达式对目标对象进行额外处理
     * <p>
     * 例如OrgUser 转为 UserVO,并设置unitId,unitName,
     * <p>
     * UserVO userVO = BeanUtils.convertFrom(orgUser, UserVO.class, (t) -> { t.setUnitId(34); t.setUnitName("基础中心"); });
     *
     * @param source       源对象
     * @param requiredType 目标对象的类型
     * @param consumer     lambda函数，可对目标对象进行额外处理
     * @param <T>          目标对象泛型
     * @param <E>          源对象泛型
     * @return 目标对象
     */
    public static <T, E> T convertFrom(E source, Class<T> requiredType, Consumer<T> consumer) {
        if (source == null) {
            return null;
        }
        T target;
        try {
            // 目标对象必须有无参构造器
            target = requiredType.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, target);
            consumer.accept(target);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorEnum.ERROR_DATA_TRANSFORM_FAILED, "Bean转换异常");
        }
        return target;
    }

    /**
     * 增强函数传递的可拓展性
     *
     * @param sourceList
     * @param requiredType
     * @param function
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T, E> List<T> convertListFromFun(List<E> sourceList, Class<T> requiredType, DTOFunction<E, T> function) {
        if (sourceList == null) {
            return null;
        }
        List<T> targetList = new ArrayList<>();
        if (!sourceList.isEmpty()) {
            sourceList.forEach(source -> targetList.add(convertFromFun(source, requiredType, function)));
        }
        return targetList;
    }

    /**
     * 增强函数传递的可拓展性
     *
     * @param source
     * @param requiredType
     * @param function
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T, E> T convertFromFun(E source, Class<T> requiredType, DTOFunction<E, T> function) {
        if (source == null) {
            return null;
        }
        T target;
        try {
            // 目标对象必须有无参构造器
            target = requiredType.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(source, target);
            target = function.apply(source, target);
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
            throw new BusinessException(ErrorEnum.ERROR_DATA_TRANSFORM_FAILED, "Bean转换异常");
        }
        return target;
    }

    public static <T, E> T convertFrom(E source, Class<T> requiredType) {
        return convertFrom(source, requiredType, t -> {
        });
    }

    public interface DTOFunction<T, R> {
        R apply(T t, R r);
    }

}
